import { showWxToast } from '../utils/index'

const TEMPLATEID = 'uDvjb_IqKELTI2NFD2uwyXze9pMDAxda1go-uFjQzqY';
const TEMPLATEID2 = 'smK_K6cNxrFRgSPW_YPDzMedFBZa6DfxAqv2inEsYvU';
// 检查小程序更新
export function checkSystemUpdate() {
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        console.log('onCheckForUpdate',res.hasUpdate)
    })

    updateManager.onUpdateReady(function () {
        wx.showModal({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success: function (res) {
                if (res.confirm) {
                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                    updateManager.applyUpdate()
                }
            }
        })
    })

    updateManager.onUpdateFailed(function () {
        // 新版本下载失败
        showWxToast('新版本下载失败!');
    })
}

//获取系统信息
export function getSystemInfo() {
    return new Promise((resolve, reject) => {
        wx.getSystemInfo({
            success: (result) => {
                resolve(result);
            },
            fail: () => {
                reject(1);
            }
        });
    })
}

//获取用户的当前设置(是否授权过等信息)
export function getSetting() {
    return new Promise((resolve, reject) => {
        wx.getSetting({
            success: (result) => {
                resolve(result);
            },
            fail: () => {
                reject(1);
            }
        });
    })
}

//询问订阅消息
export function getSubscribeMessage() {
    return new Promise((resolve, reject) => {
        wx.requestSubscribeMessage({
            tmplIds: [TEMPLATEID,TEMPLATEID2],
            success: (result) => {
                resolve(result[TEMPLATEID,TEMPLATEID2]);
            },
            fail: () => {
                reject(1);
            }
        });
    })
}

// 下载文件
export function wxDownloadFile(filePath) {
    return new Promise((resolve,reject) => {
        wx.downloadFile({
            url: filePath,
            success: (res) => {
                resolve(res);
            },
            fail: (err) => {
                reject(err);
            },
        });
    });
}

// 文件保存到相册
export function wxSaveFileToAlbum(tmpFilePath) {
    return new Promise((resolve,reject) => {
        wx.saveImageToPhotosAlbum({
            filePath: tmpFilePath,
            success: (res) => {
                resolve(res);
            },
            fail: (err) => {
                reject(err);
            },
        });
    });
}